{extend name="common:base" /}

{block name="title"}{$config.site_name}{/block}

{block name="css"}
<link href="/static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<link href="/static/bootstrap-fileinput/css/fileinput.min.css" rel="stylesheet">
<link href="/static/fontawesome-free/css/all.min.css" rossorigin="anonymous" rel="stylesheet">
{/block}

{block name="main"}
<div class="mdui-container">
  <main>
    <div class="upload-container">
      {if $config.notice}
      <div class="alert alert-info alert-dismissible fade show">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        {$config.notice|raw}
      </div>
      {/if}
      <div class="title">
        <h1>Image Upload</h1>
        <p>最大可上传 {:format_size($config.upload_max_size)} 的图片，单次同时可选择 {$config.upload_single_num} 张。本站已托管 {$images_count} 张图片。</p>
      </div>
      <form action="" method="post" enctype="multipart/form-data">
        <input id="image" style="display: none;" type="file" multiple name="image" accept="image/*">
      </form>
      <div class="success-info">
        <div class="mdui-tab mdui-tab-scrollable" mdui-tab>
          <a href="#code-url" class="mdui-ripple mdui-tab-active">URL</a>
          <a href="#code-html" class="mdui-ripple">HTML</a>
          <a href="#code-bbcode" class="mdui-ripple">BBCode</a>
          <a href="#code-markdown" class="mdui-ripple">Markdown</a>
          <a href="#code-markdown-with-link" class="mdui-ripple">Markdown with link</a>
        </div>
        <div id="code-url"><ul></ul></div>
        <div id="code-html"><ul></ul></div>
        <div id="code-bbcode"><ul></ul></div>
        <div id="code-markdown"><ul></ul></div>
        <div id="code-markdown-with-link"><ul></ul></div>
      </div>
    </div>
    {if 0 == $config.allowed_tourist_upload and !$user}
    <div class="mask">
      <div class="content">
        <div class="panel-box mdui-color-white mdui-text-center">
          <h6 class="mdui-m-b-2">请登录后体验</h6>
          <div class="mdui-btn-group">
            <a href="{:url('auth/login')}" class="mdui-btn mdui-ripple mdui-color-cyan mdui-text-color-white mdui-btn-dense">登录</a>
            <a href="{:url('auth/register')}" class="mdui-btn mdui-ripple mdui-color-green mdui-text-color-white mdui-btn-dense">注册</a>
          </div>
        </div>
      </div>
    </div>
    {/if}
  </main>
</div>
<div class="mdui-fab-wrapper" id="fab-buttons">
  <button class="mdui-fab mdui-ripple mdui-color-blue-700 mdui-fab-hide copy" id="copy-all">
    <i class="mdui-icon material-icons">&#xe14d;</i>
  </button>
</div>
{/block}
{block name="js"}
<script src="/static/bootstrap/js/bootstrap.min.js"></script>
<script src="/static/bootstrap-fileinput/js/plugins/piexif.min.js"></script>
<script src="/static/bootstrap-fileinput/js/plugins/sortable.min.js"></script>
<script src="/static/bootstrap-fileinput/js/plugins/purify.min.js"></script>
<script src="/static/bootstrap-fileinput/js/fileinput.min.js"></script>
<script src="/static/bootstrap-fileinput/themes/fas/theme.min.js"></script>
<script src="/static/bootstrap-fileinput/js/locales/zh.js"></script>
<script>
  var clipboard = new ClipboardJS('.copy', {
    text: function(trigger) {
      // copy all
      if (trigger.id === 'copy-all') {
        var str = '';
        var id = $('.success-info a.mdui-tab-active').attr('href');
        $(id + ' li').each(function (index, item) {
          if (index > 0) {
            str += '\r\n';
          }
          str += $(item).text();
        });
        return str;
      }

      return $(trigger).parent('li').text();
    }
  });

  clipboard.on('success', function(e) {
    app.msg(true, '复制成功');
  });

  clipboard.on('error', function(e) {
    app.msg(false, '复制失败');
  });

  var toggleCopyAllBtn = function () {
    $('#copy-all')[$('#code-url ul li').length ? 'removeClass' : 'addClass']('mdui-fab-hide');
  }

  var sort = function (uls) {
    for (var i = 0; i < uls.length; i++) {
      var sortEle = $(uls[i]).find('li').sort(function (a, b) {
        return $(a).data('index') > $(b).data('index') ? 1 : -1;
      });
      $(uls[i]).empty().append(sortEle);
    }
  };

  $("#image").fileinput({
    uploadUrl: "{:url('upload/upload')}",
    language: "zh",
    theme: "fas",
    previewFileType: "image",
    autoOrientImage: true,
    uploadAsync: true,
    overwriteInitial: false,
    maxFileSize: "{$config.upload_max_size / 1024}",// kb
    maxFileCount: "{$config.upload_single_num}",
    showCaption: true,
    dropZoneEnabled: true,
    browseIcon: "<i class=\"fas fa-images\"></i> ",
    allowedFileExtensions: JSON.parse('{:json_encode(explode(",", filter_comma($config.upload_allowed_exts)))}'),
  }).on("fileuploaded", function(event, data, previewId, index) {
    var form = data.form, files = data.files, extra = data.extra, response = data.response, reader = data.reader;
    if(200 === response.code) {
      $("#code-url ul").prepend("<li data-index=" + index + ">" + response.data.url + "<i class=\"copy iconfont icon-copy\"></i></li>");
      $("#code-html ul").prepend("<li data-index=" + index + ">&lt;img src=\"" + response.data.url + "\" alt=\"" + response.data.name + "\" title=\"" + response.data.name + "\" /&gt;<i class=\"copy iconfont icon-copy\"></i></li>");
      $("#code-bbcode ul").prepend("<li data-index=" + index + ">[img]" + response.data.url + "[/img]<i class=\"copy iconfont icon-copy\"></i></li>");
      $("#code-markdown ul").prepend("<li data-index=" + index + ">![" + response.data.name + "](" + response.data.url + ")<i class=\"copy iconfont icon-copy\"></i></li>");
      $("#code-markdown-with-link ul").prepend("<li data-index=" + index + ">[![" + response.data.name + "](" + response.data.url + ")](" + response.data.url + ")<i class=\"copy iconfont icon-copy\"></i></li>");

      // 排序
      sort(['#code-url ul', '#code-html ul', '#code-bbcode ul', '#code-markdown ul', '#code-markdown-with-link ul']);

      $(".success-info").css("width", "inherit").css('display', 'block');
      if (response.data.quota && response.data.use_quota) {
        $('.quota-container progress').attr('max', response.data.quota);
        $('.quota-container progress').val(response.data.use_quota);
        $('.quota-container span.quota').text(app.bytesToSize(response.data.quota));
        $('.quota-container span.use-quota').text(app.bytesToSize(response.data.use_quota));
      }
      toggleCopyAllBtn();
    } else if (500 === response.code) {
      mdui.alert(response.msg, '发生异常');
    } else {
      mdui.alert(response.msg);
    }
  }).on("filecleared", function (event, data, msg) {
    // 清空
    $('.success-info')
      .css('display', 'none')
      .find('#code-url, #code-html, #code-bbcode, #code-markdown, #code-markdown-with-link')
      .find('ul')
      .html('');
    toggleCopyAllBtn();
  });
  $('#image').css("display", "block");

  $('.success-info ul').on('mouseenter', "li", function() {
    $('.file-preview .file-drop-zone .file-preview-thumbnails > [data-template=image]').eq($(this).data('index')).addClass('hover');
  }).on('mouseout', 'li', function () {
    $('.file-preview .file-drop-zone .file-preview-thumbnails > [data-template=image]').eq($(this).data('index')).removeClass('hover');
  });

</script>
{if 1 == $config.allowed_tourist_upload or $user}
<script>
  // Originate from https://sm.ms
  document.addEventListener('paste', function (event) {
    var isChrome = false;
    if ( event.clipboardData || event.originalEvent ) {
      var clipboardData = (event.clipboardData || event.originalEvent.clipboardData);
      if ( clipboardData.items ) {
        // for chrome
        var  items = clipboardData.items,
          len = items.length,
          blob = null;
        isChrome = true;

        event.preventDefault();

        let images = [];
        for (var i = 0; i < len; i++) {
          if (items[i].type.indexOf("image") !== -1) {
            blob = items[i].getAsFile();
            var ext = blob.name.substr(blob.name.lastIndexOf(".") + 1)
            images.push(new File([blob], new Date().getTime() + "." + ext, {
              type: blob.type
            }));
          }
        }
        if(images.length > 0) {
          uploadBlobFile(images);
        }
        if ( blob !== null ) {
          var reader = new FileReader();
          reader.onload = function (event) {
            var base64_str = event.target.result;
          }

        }
      } else {
        //for firefox
      }
    } else {
    }
  });

  function uploadBlobFile(images) {
    var form = $("#image");
    mdui.confirm('是否上传粘贴的图片?', function() {
      $('.file-drop-zone-title').remove();
      form.fileinput('readFiles', images);
      setTimeout(function () {
        form.fileinput('upload');
      }, 400)
    }, function () {}, {
      confirmText: '确定',
      cancelText: '取消'
    });
  }
</script>
{/if}
{/block}
